<template>
    <div class="log-page">
        <header>
            <el-button @click="data.dialogFormVisible = true"><el-icon style="margin-right: 5px;">
                    <Plus />
                </el-icon>日报</el-button>
            <h1>看日志</h1>
            <div class="tabs">
                <button :class="{ active: tab === 'received' }" @click="adopt">我收到的</button>
                <button :class="{ active: tab === 'sent' }" @click="sendDaily">我发出的</button>
                <button :class="{ active: tab === 'team' }" @click="team">我的团队</button>
            </div>
        </header>

        <div class="logs" v-show="data.isShow">
            <div v-for="log in filteredLogs" :key="log.id" class="log-item" @click="lookDaily(log.id)">
                <div class="log-header">
                    <span>{{ log.date }}</span>
                    <span>{{ log.dayOfWeek }}</span>
                </div>
                <div class="log-content">
                    <h2>{{ log.title }}</h2>
                    <p>{{ log.summary }}</p>
                    <div class="log-footer">
                        <span>{{ log.readCount }} 已读</span>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <el-dialog v-model="data.dialogVisible" title="日报" width="1100" :before-close="handleClose">

        <v-card class="view" elevation="8" style="border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
            <v-card-text class="text--primary" style="padding: 16px;">
                <h3 style="font-weight: bold; color: #333; margin-bottom: 8px;">{{ data.viweDaily.dailyName }}</h3>
                <p style="line-height: 1.6; color: #555; margin-bottom: 16px;text-indent: 2em;">{{
                    data.viweDaily.content }}</p>
                <p style="color: #777; margin-bottom: 16px;">访问次数: {{ data.viweDaily.readCount }}</p>
                <div style="border-top: 1px solid #eee; padding-top: 10px;">
                    <h4 style="color: #888; margin-bottom: 8px;">附加信息</h4>
                    <p style="color: #999;">日期: {{ data.viweDaily.date }}</p>
                </div>
            </v-card-text>
            <el-button type="primary" style="position: absolute; left: 570px;"
                @click="downloadDaily(data.viweDaily.id)">下载</el-button>
        </v-card>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="data.dialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="data.dialogFormVisible" title="发表日报" width="1000">
        <el-form :model="data.form">
            <el-form-item label="标题" size="large" :label-width="formLabelWidth">
                <el-input v-model="data.form.dailyName" autocomplete="off" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="摘要" size="large" :label-width="formLabelWidth">
                <el-input v-model="data.form.summary" autocomplete="off" placeholder="请输入摘要" />
            </el-form-item>
            <el-form-item label="内容">
                <el-input v-model="data.form.content" :label-width="formLabelWidth" placeholder="请输入内容" show-word-limit
                maxlength="1000" type="textarea" :rows="20" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="makeSureDaily">
                    发表
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 刷新特效 等到等等 -->
    <div v-if="data.refreshing" class="refresh-animation">
        <div class="circle"></div>
    </div>
</template>

<script setup>
import { addDaily, downloadDailyTxtFile, getDaily, getDailyData, getDailyViewId, getTeamSendDaily, getUserSendDaily } from '@/api/daily';
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import Log from '../log/Log.vue';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

const userObj = useUserStore()
const tab = ref('received')
const filter = ref('all')
const unreadOnly = ref(false)
const data = reactive({
    logs: [], //日报容器

    pageNum: 1,
    pageSize: 15,
    total: 0, //总数量
    lastScrollTop: 0,
    scrollThreshold: -1000,
    refreshing: false, // 刷新的控制器

    viweDaily: {}, //展示日报的容器
    isShow: true, //是否展示日报列表
    dialogVisible: false,

    dialogFormVisible: false,
    form: {},

})


const startRefresh = () => {
    data.refreshing = true;
    // 模拟异步操作，例如API调用
    setTimeout(() => {
        data.refreshing = false;
    }, 1400)
};

onMounted(() => {
    document.querySelector('.neiRong').addEventListener('scroll', handleScroll)
    const element = document.querySelector('.neiRong');
    const children = element.getElementsByClassName('log-page')
    children[0].addEventListener('scroll', handleScroll)
})

function getTodayWeekday() {
  const weekdays = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
  const today = new Date() 
  const weekdayIndex = today.getDay()
  return weekdays[weekdayIndex]
}



//确定发表日报
const makeSureDaily = async () => {
    data.dialogFormVisible = false
    data.form.employeeId = userObj.user.id
    data.form.departmentId = userObj.user.departmentId
    data.form.title = userObj.user.name + '的日报'
    if(data.form.departmentId == null){
        data.form.departmentId = 0 //权限高的 departmentId 默认为 0
    }
    data.form.dayOfWeek = getTodayWeekday() //今天的星期日期 
    await addDaily(data.form).then(res => {
        if(res.data.code == 200){
            ElMessage.success('发表')
            load()
        }else{
            ElMessage.error('发表失败')
        }
    })
}

//取消发表日报
const cancel = () => {
    data.dialogFormVisible = false
}

//我收到的
const adopt = () => {
    tab.value = 'received'
    load()
}

//我发出的
const sendDaily = async () => {
    tab.value = 'sent'
    const userObj = useUserStore()
    await getUserSendDaily(userObj.user.id).then(res => {
        data.logs = res.data.data.list
    })
}

//我的团队
const team = async () => {
    tab.value = 'team'
    const userObj = useUserStore()
    await getTeamSendDaily(userObj.user.id, userObj.user.departmentId).then(res => {
        console.log(res);
        data.logs = res.data.data
    })
}


//点击下载日报的功能
const downloadDaily = (id) => {
    downloadDailyTxtFile(id).then(res => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'output.txt'); // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    })

}


//点击展示日报功能
const lookDaily = (id) => {
    getDailyViewId(id).then(res => {
        data.viweDaily = res.data.data
        data.dialogVisible = true
    })
}


//懒加载 刷新滚轮来刷新页面
const handleScroll = () => {
    const element = document.querySelector('.neiRong');
    const children = element.getElementsByClassName('log-page')
    //当前子子类[当前的table 与 顶部的距离]
    const tableTop = Array.from(children)[0].getBoundingClientRect().y //获取该元素位于顶部的y轴的距离    
    if (tableTop < data.scrollThreshold) {
        startRefresh()
        data.scrollThreshold = data.scrollThreshold * 2
        data.pageSize = data.pageSize * 2
        setTimeout(() => {
            load()
        }, 1500)
    }
    // const childrenArray = Array.from(children)
    // childrenArray.forEach(child => {
    //     const rect = child.getBoundingClientRect(); // 获取元素相对于视口的位置和尺寸
    //     console.log({
    //         element: child,
    //         top: rect.top,        // 元素顶部相对于视口顶部的距离
    //         left: rect.left,       // 元素左侧相对于视口左侧的距离
    //         width: rect.width,     // 元素宽度
    //         height: rect.height,   // 元素高度
    //         bottom: rect.bottom,   // 元素底部相对于视口顶部的距离
    //         right: rect.right      // 元素右侧相对于视口左侧的距离
    //     });
    // });
}


const filteredLogs = computed(() => {
    return data.logs.filter(log => {
        if (unreadOnly.value && log.readCount > 0) return false
        return true
    })
})

const load = async () => {
    await getDaily(data.pageNum, data.pageSize).then(res => {
        data.logs = res.data.data.list
    })
}

load()

</script>

<style scoped>
/* 刷新的 */
.refresh-animation {
    width: 60px;
    height: 60px;
    margin: 20px auto;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.circle {
    width: 100%;
    height: 100%;
    border: 2px solid rgba(51, 51, 51, 0.3);
    border-radius: 50%;
    position: absolute;
    top: 0;
    left: 0;
    animation: spin 1.5s ease-in-out infinite;
}

.circle::before {
    content: '';
    display: block;
    width: 80%;
    height: 80%;
    background: linear-gradient(135deg, #6e48aa, #9d50bb);
    border-radius: 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    animation: pulse 1s ease-in-out infinite;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

@keyframes pulse {

    0%,
    100% {
        transform: scale(1);
        opacity: 1;
    }

    50% {
        transform: scale(1.1);
        opacity: 0.7;
    }
}


.log-page {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
        Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    padding: 20px;
    background-color: #f9f9f9;
    color: #333;
}

header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    padding: 10px;
    border-bottom: 1px solid #e0e0e0;
}

.tabs button {
    margin-right: 10px;
    padding: 8px 12px;
    border: none;
    background-color: #f0f0f0;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.tabs button.active {
    background-color: #007bff;
    color: white;
}

.logs {
    margin-top: 20px;
}

.log-item {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 25px;
    cursor: pointer;
}

.log-header {
    display: flex;
    justify-content: space-between;
    font-size: 0.9em;
    color: #666;
    margin-bottom: 10px;
}

.log-content h2 {
    margin: 0;
    font-size: 1.1em;
    color: #007bff;
}

.log-content p {
    margin: 10px 0;
    color: #555;
}

.log-footer {
    display: flex;
    justify-content: space-between;
    font-size: 0.9em;
    color: #666;
}

/* 展示日报   ----------------*/
.view {
    display: block;
    position: relative;
    /* 改为相对定位 */
    width: 90%;
    /* 设置宽度为视口宽度的90% */
    max-width: 600px;
    /* 最大宽度为600px */
    margin: 20px auto;
    /* 居中对齐 */
    padding: 20px;
    /* 内边距 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    /* 圆角 */
    background-color: #fff;
    /* 背景颜色 */
}

/* 日报卡片容器样式 */
.daily-report-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    background-color: #fff;
}

/* 日报标题样式 */
.daily-report-title {
    background-color: #f5f5f5;
    padding: 16px;
    font-size: 1.2em;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #e0e0e0;
}

/* 日报内容样式*/
.daily-report-content {
    padding: 16px;
    font-size: 1em;
    line-height: 1.6;
    color: #555;
}

.daily-report-content h3 {
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
}

.daily-report-content p {
    margin-bottom: 16px;
    color: #777;
}

.daily-report-content div {
    border-top: 1px solid #eee;
    padding-top: 10px;
}

.daily-report-content h4 {
    color: #888;
    margin-bottom: 8px;
}

.daily-report-content p:last-child {
    margin-bottom: 0;
}

/* 操作按钮样式 */
.daily-report-actions {
    background-color: #f5f5f5;
    padding: 8px;
    display: flex;
    justify-content: flex-end;
    /* 按钮靠右对齐 */
}

.daily-report-actions button {
    margin-left: 8px;
    /* 按钮之间的间距 */
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    font-size: 1em;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s;
}

.daily-report-actions button:hover {
    background-color: #e0e0e0;
}

.daily-report-actions .view-details {
    background-color: #007bff;
    color: #fff;
}

.daily-report-actions .view-details:hover {
    background-color: #0056b3;
}

.daily-report-actions .share {
    background-color: #6c757d;
    color: #fff;
}

.daily-report-actions .share:hover {
    background-color: #5a6268;
}
</style>